//
//  Project_Step3ViewController.m
//  CMVRFForIOS
//
//  Created by zhangnorman on 15/4/11.
//  Copyright (c) 2015年 hvacapp. All rights reserved.
//

#import "Project_Step3ViewController.h"
#import "Project_TabViewController.h"
#import "BottomActionView.h"
#import "Project_Step2ViewController.h"
#import "Project_Step3ViewController.h"
#import "Project_Step4ViewController.h"
#import "Project_Step45ViewController.h"
#import "Project_Step5ViewController.h"
#import "Project_Step6ViewController.h"
#import <TPKeyboardAvoidingTableView.h>
#import "GuidData.h"
#import "ProjectData.h"
#import "ProjectManager.h"
#import <MBProgressHUD.h>
#import "ProjectCalc.h"
#import "QrjhqInfoData.h"
#import "KqnRsjInfoData.h"
#import "HttpTool.h"
#import "Project_Step8ViewController.h"
#import "ProjectContentViewController.h"


@interface Project_Step3ViewController () {
    MBProgressHUD *HUD;
    int uploadSWJStatus; //上传选择的系列状态 0：初始状态（失败后回到初始状态） 1：上传中  2：成功
    int uploadQXSYKTStatus; //上传选择的系列状态 0：初始状态（失败后回到初始状态） 1：上传中  2：成功
    int uploadKQNRSJStatus; //上传选择的系列状态 0：初始状态（失败后回到初始状态） 1：上传中  2：成功
    int uploadQRJHQStatus; //上传选择的系列状态 0：初始状态（失败后回到初始状态） 1：上传中  2：成功
    BOOL infoIsModified;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) BottomActionView *footerView;


@property (nonatomic,strong) NSMutableArray *dataSource;
@property (nonatomic,strong) NSMutableDictionary *chooses;


@end

@implementation Project_Step3ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initData];
    [self setupViews];
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    [self.footerView updateCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
}

/**
 *  初始化数据
 */
- (void)initData {
    self.dataSource = [NSMutableArray new];
    self.chooses = [NSMutableDictionary new];
}


#pragma mark - 初始化视图
- (void)setupViews{
    self.title = @"系统配置";
    
    //自定义返回按钮
    UIBarButtonItem *backBtn = [[UIBarButtonItem alloc] initWithTitle:@"项目" style:UIBarButtonItemStyleDone target:self action:@selector(onBackToProject)];
    self.navigationItem.leftBarButtonItem = backBtn;
    
    //底部的上一步，下一步按钮
    self.footerView = [[BottomActionView alloc]initWithFrame:CGRectMake(0, self.view.height - KAction_Bar_Height - kNavigation_Bar_Height - kStatus_Bar_Height, kScreen_Width, KAction_Bar_Height)];
    if (iPhone_X) {
        self.footerView.y -= 34;
    }
    __block Project_Step3ViewController *tmp = (Project_Step3ViewController*)self;
    [self.footerView addLeftBtnBlock:^(id obj) {
        //需要跳过选择房间编辑的页面的步骤，所以返回到第一个页面
        [[ProjectManager manager]goLastPage];
        for (UIViewController *item in tmp.navigationController.viewControllers) {
            if ([item isKindOfClass:[Project_Step2ViewController class]]) {
                [tmp.navigationController popToViewController:item animated:YES];
            }
        }
    }];
    [self.footerView addRightBtnBlock:^(id obj) {
        if (![tmp checkUserSelection]) {
            return;
        }
        if (![tmp checkModification]) {
            //没有修改，直接下一步
            [[ProjectManager manager]goNextPage];
            [tmp loadNextPage];
            return;
        }
        [MBProgressHUD showMessage:@"数据提交中..." toView:self.view];
        [tmp applySystemConfig:^(BOOL result) {
            [MBProgressHUD hideHUDForView:self.view];
            if (result) {
                [[ProjectManager manager]goNextPage];
                [tmp loadNextPage];
            } else {
                [Tools showMessageCenter:@"应用项目系统配置失败！"];
            }
        }];
        
    }];
    [self.footerView setLeftBtnTitle:@"上一步" andRightBtnTitle:@"下一步" andCenterTitle:[[ProjectManager manager]getCurrentStepInfo]];
    [self.view addSubview:self.footerView];
    
    //列表
    self.tableView = [[UITableView alloc] initWithFrame:[UIView frameWithOutNavBottom] style:UITableViewStylePlain];
    self.tableView.backgroundColor = CM_TABLE_BG_COLOR;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    //去掉多余的分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    //下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
    [self.tableView.mj_header beginRefreshing];
}

- (void)loadData {
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    [param setObject:kProject.project_id forKey:@"project_id"];
    [param setObject:[AccountManager manager].token forKey:@"token"];
    [HttpTool get:HTTP_POST_PROJECT_CONFIG params:param success:^(NSDictionary *responseObj) {
        [self.tableView.mj_header endRefreshing];
        self.dataSource = [responseObj objectForKey:@"result"];
        for (NSDictionary *item in self.dataSource) {
            [self.chooses setObject:[item objectForKey:@"choose"] forKey:[item objectForKey:@"name"]];
        }
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        [self.tableView.mj_header endRefreshing];
    }];
}

- (BOOL)checkUserSelection {
    //参数
    if (![Tools isEmpty:[self.chooses objectForKey:@"main_equip_series"]]) {
        if ([Tools isEmpty:[self.chooses objectForKey:@"loop_type"]]) {
            [Tools showMessageCenter:@"需要选择循环方式"];
            return NO;
        }
    }
    if ([Tools isEmpty:[self.chooses objectForKey:@"main_equip_series"]]
        && [Tools isEmpty:[self.chooses objectForKey:@"kqnrsj_series"]]
        && [Tools isEmpty:[self.chooses objectForKey:@"qrjhq_series"]]
        && [Tools isEmpty:[self.chooses objectForKey:@"water_cleaner_series"]]) {
        [Tools showMessageCenter:@"必须要选择一种设备系列！"];
        return NO;
    }
    return YES;
}

- (BOOL)checkModification {
    //参数
    if (![Tools isEmpty:[self.chooses objectForKey:@"main_equip_series"]]) {
        if ([Tools isEmpty:kProject.main_equip_series]
            || ![[self.chooses objectForKey:@"main_equip_series"] isEqualToString:kProject.main_equip_series]) {
            return YES;
        }
    } else {
        if (![Tools isEmpty:kProject.main_equip_series]) {
            return YES;
        }
    }
    if (![Tools isEmpty:[self.chooses objectForKey:@"loop_type"]]) {
        if ([Tools isEmpty:kProject.loop_type]
            || ![[self.chooses objectForKey:@"loop_type"] isEqualToString:kProject.loop_type]) {
            return YES;
        }
    } else {
        if (![Tools isEmpty:kProject.loop_type]) {
            return YES;
        }
    }
    if (![Tools isEmpty:[self.chooses objectForKey:@"qrjhq_series"]]) {
        if ([Tools isEmpty:kProject.qrjhq_series]
            || ![[self.chooses objectForKey:@"qrjhq_series"] isEqualToString:kProject.qrjhq_series]) {
            return YES;
        }
    } else {
        if (![Tools isEmpty:kProject.qrjhq_series]) {
            return YES;
        }
    }
    if (![Tools isEmpty:[self.chooses objectForKey:@"kqnrsj_series"]]) {
        if ([Tools isEmpty:kProject.kqnrsj_series]
            || ![[self.chooses objectForKey:@"kqnrsj_series"] isEqualToString:kProject.kqnrsj_series]) {
            return YES;
        }
    } else {
        if (![Tools isEmpty:kProject.kqnrsj_series]) {
            return YES;
        }
    }
    if (![Tools isEmpty:[self.chooses objectForKey:@"water_cleaner_series"]]) {
        if ([Tools isEmpty:kProject.water_cleaner_series]
            || ![[self.chooses objectForKey:@"water_cleaner_series"] isEqualToString:kProject.water_cleaner_series]) {
            return YES;
        }
    } else {
        if (![Tools isEmpty:kProject.water_cleaner_series]) {
            return YES;
        }
    }
    return NO;
}

- (void)applySystemConfig:(void (^)(BOOL))result{
    [self.chooses setObject:kProject.project_id forKey:@"project_id"];
    [HttpClient postWithUrl:HTTP_POST_PROJECT_CONFIG_APPLY token:[AccountManager manager].token paramDic:self.chooses resultClass:[ProjectData class] success:^(ProjectData *obj) {
        kProject.main_equip_series = [self.chooses objectForKey:@"main_equip_series"];
        kProject.kqnrsj_series = [self.chooses objectForKey:@"kqnrsj_series"];
        kProject.qrjhq_series = [self.chooses objectForKey:@"qrjhq_series"];
        kProject.water_cleaner_series = [self.chooses objectForKey:@"water_cleaner_series"];
        kProject.loop_type = [self.chooses objectForKey:@"loop_type"];
        
        if (obj.main_equip_systems != nil) {
             kProject.main_equip_systems = [obj.main_equip_systems mutableCopy];
        }
        if (obj.qrjhq_systems != nil) {
            kProject.qrjhq_systems = [obj.qrjhq_systems mutableCopy];
        }
        if (obj.kqnrsj_systems != nil) {
            kProject.kqnrsj_systems = [obj.kqnrsj_systems mutableCopy];
        }
        if (obj.water_cleaner_equips != nil) {
            kProject.water_cleaner_equips = [obj.water_cleaner_equips mutableCopy];
        }
        if (obj.rooms != nil && obj.rooms.count > 0) {
            kProject.rooms = [obj.rooms mutableCopy];
        }
        result(YES);
    } failure:^(NSError *error) {
        result(NO);
    }];
}

- (void)loadNextPage {
    //先更新总步骤信息
    [[ProjectManager manager]updateTotalSteps];
    
    if (![Tools isEmpty:kProject.main_equip_series]) {
        Project_Step4ViewController *view = [Project_Step4ViewController new];
        [self.navigationController pushViewController:view animated:YES];
    } else if (![Tools isEmpty:kProject.qrjhq_series]) {
        Project_Step45ViewController *view = [Project_Step45ViewController new];
        [self.navigationController pushViewController:view animated:YES];
    } else if (![Tools isEmpty:kProject.kqnrsj_series]) {
        Project_Step5ViewController *view = [Project_Step5ViewController new];
        [self.navigationController pushViewController:view animated:YES];
    } else if (![Tools isEmpty:kProject.water_cleaner_series]) {
        Project_Step6ViewController *view = [Project_Step6ViewController new];
        [self.navigationController pushViewController:view animated:YES];
    } else {
        //报告页
        Project_Step8ViewController *view = [Project_Step8ViewController new];
        view.userName = kProject.name;
        view.project_id = kProject.project_id;
        view.project_name = kProject.project_name;
        [self.navigationController pushViewController:view animated:YES];
    }
    
}




#pragma mark - 事件响应函数
/**
 *  直接跳转到项目页面
 */
-(void) onBackToProject{
    //返回到首页
    for (UIViewController *tmp in self.navigationController.viewControllers) {
        if ([tmp isKindOfClass:[Project_TabViewController class]]) {
            [(Project_TabViewController*)tmp refreshData];
            [self.navigationController popToViewController:tmp animated:YES];
        }
    }
}

#pragma mark - tableView显示设置数据
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.dataSource.count;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSDictionary *dic = [self.dataSource objectAtIndex:section];
    if (dic != nil) {
        NSMutableArray *series = [dic objectForKey:@"series"];
        if (series != nil) {
            return series.count;
        }
    }
    return 0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *identifier = @"ProjectStep2Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    cell.textLabel.textColor = CM_TABLE_TITLE_COLOR;
    cell.textLabel.font = [UIFont systemFontOfSize:kListTitleFontSize];
    
    NSDictionary *dic = [self.dataSource objectAtIndex:indexPath.section];
    NSString *choose = [self.chooses objectForKey:[dic objectForKey:@"name"]];
    if (dic != nil) {
        NSMutableArray *series = [dic objectForKey:@"series"];
        NSDictionary *item = [series objectAtIndex:indexPath.row];
        cell.textLabel.text = [item objectForKey:@"Series"];
        if (![Tools isEmpty:choose] && [choose containsString:cell.textLabel.text]) {
            cell.accessoryType = UITableViewCellAccessoryCheckmark;
        } else {
            cell.accessoryType = UITableViewCellAccessoryNone;
        }
    }
    return cell;
}


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSDictionary *dic = [self.dataSource objectAtIndex:indexPath.section];
    NSString *choose = [self.chooses objectForKey:[dic objectForKey:@"name"]];
    if (dic != nil) {
        NSMutableArray *series = [dic objectForKey:@"series"];
        NSDictionary *item = [series objectAtIndex:indexPath.row];
        if (indexPath.section == 4) {
            //净水器可以多选
            NSMutableArray *b = [NSMutableArray new];
            if (![Tools isEmpty:choose] && [choose containsString:[item objectForKey:@"Series"]]) {
                NSArray *a = [choose componentsSeparatedByString:@","];
                for (NSString *i in a) {
                    if (![i isEqualToString:[item objectForKey:@"Series"]]) {
                        [b addObject:i];
                    }
                }
            } else {
                [b addObject:[item objectForKey:@"Series"]];
                if (![Tools isEmpty:choose]) {
                    NSArray *a = [choose componentsSeparatedByString:@","];
                    for (NSString *i in a) {
                        [b addObject:i];
                    }
                }
            }
            [self.chooses setObject:[b componentsJoinedByString:@","] forKey:[dic objectForKey:@"name"]];
        } else {
            if ([[item objectForKey:@"Series"] isEqualToString:choose]) {
                [self.chooses setObject:@"" forKey:[dic objectForKey:@"name"]];
            } else {
                [self.chooses setObject:[item objectForKey:@"Series"] forKey:[dic objectForKey:@"name"]];
            }
        }
        
        
        if (indexPath.section == 0) {
            //循环形式要联动
            if (![Tools isEmpty:[self.chooses objectForKey:[dic objectForKey:@"name"]]]) {
                if ([Tools isEmpty:[self.chooses objectForKey:@"loop_type"]]) {
                    [self.chooses setObject:@"单循环" forKey:@"loop_type"];
                    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
                }
            } else {
                [self.chooses setObject:@"" forKey:@"loop_type"];
                [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
            }
        }
    }
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, CGFLOAT_MIN)];
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return DEFAULT_SECTION_HEIGHT*2;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreen_Width, DEFAULT_SECTION_HEIGHT*2)];
    view.backgroundColor = [UIColor groupTableViewBackgroundColor];
    
    NSDictionary *dic = [self.dataSource objectAtIndex:section];
    NSString *title = [dic objectForKey:@"title"];
    UILabel *label = [UILabel labelSingleLineFontSize:kActionBarFontSize content:title];
    label.x = CELL_PADDING_LEFT;
    label.centerY = view.height/2;
    label.textColor = CM_ORANGE_COLOR;
    [view addSubview: label];
    return view;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
